package com.example.srm.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.srm.constant.SysUserTokenConstant;
import com.example.srm.domain.SysUserToken;
import com.example.srm.auth.service.SysUserTokenService;
import com.example.srm.auth.mapper.SysUserTokenMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 *
 */
@Service
@Slf4j
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenMapper, SysUserToken>
    implements SysUserTokenService{

    //默认失效时间 12小时
    private Long ExpireTimeSecond = 12 * 60 * 60L;

    @Override
    public boolean createToken(String userId) {
        try{
            //这里设置token为用户id
            String token = userId;
            SysUserToken one = this.getOne(new QueryWrapper<SysUserToken>().eq(SysUserTokenConstant.TOKEN, token));
            Date now = new Date();
            Date expire = new Date(now.getTime()+ExpireTimeSecond * 1000);
            if (one == null) {
                one = new SysUserToken()
                        .setUserId(userId)
                        .setToken(token)
                        .setExpireTime(expire)
                        .setUpdateTime(now);
                this.save(one);
            }else{
                one.setUpdateTime(now).setToken(token).setExpireTime(expire);
                this.updateById(one);
            }
        }catch (Exception e){
            log.info("生成token失败",e);
            return false;
        }
        return true;
    }

    @Override
    public boolean removeByToken(String token) {
        try {
            Date now = new Date();
            boolean update = this.update(new UpdateWrapper<SysUserToken>()
                    .eq(SysUserTokenConstant.TOKEN, token)
                    .set(SysUserTokenConstant.EXPIRE_TIME, now)
                    .set(SysUserTokenConstant.UPDATE_TIME,now));
            if (!update){
                log.info("逻辑删除token失败");
                return false;
            }
        }catch (Exception e){
            log.error("逻辑删除token失败",e);
            return false;
        }
        return true;
    }
}




